#!/bin/bash
#file: genreport.sh

#fill enough lines
fill_lines(){
inputfile=$1
has_line=`cat $inputfile | wc -l`
total_line=$2
cat $1
while [ $has_line -lt $total_line ] ; do echo "E --empty--"; ((has_line++)); done
}

count_ip(){
tag_file=$1
ipfield=$2
cat $tag_file | awk '{a['$ipfield']++} END {for(b in a) print a[b]"\t"b}' | sort -nr | head -n 10 > fill_swap
#cat $1 | awk '{print $4}' | sort | uniq -c | sort -nr |  head -n 10
fill_lines fill_swap 10
rm -f fill_swap
}

find_detail(){
clientlist=$1
fmtfile=$2
for cip in `cat $clientlist | awk '{print $2}'`;do
  echo "#detail for $cip :"
  if [ $cip == "--empty--" ] ; then
  echo "--empty--"
  echo "--empty--"
  echo "--empty--"
  echo "--empty--"
  echo "--empty--"
  else
  cat $fmtfile | grep $cip | awk '{a[$3]++} END {for(b in a) print a[b]"\t"b}' | sort -nr | head -n 5 > fill_swap
  fill_lines fill_swap 5 
  rm -f fill_swap
  fi
done
}



#main start
#./genreport.sh <configfiles>

while [ $1 ] ; do
 local_dirs=`cat $1 | grep -v '#' | awk '{print $3}'`
 echo "doing $local_dirs"
  
 fmtfiles=`find $local_dirs | grep "fmtout" | grep -v "genout"`
 for fmtfile in $fmtfiles ; do
 count_ip $fmtfile '$3' > $fmtfile.genouthosts
 done
 
 fmtfiles=`find $local_dirs | grep "fmtout" | grep -v "genout" | grep "policy_denied"`
 for fmtfile in $fmtfiles ; do
 count_ip $fmtfile '$2' > $fmtfile.genoutclients
 find_detail $fmtfile.genoutclients $fmtfile > $fmtfile.genoutclients.details
 done

shift
done

